import React from "react";
import { useRequest } from "ahooks";
import { Button } from "@/components/ui/button";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Heading } from "@/components/ui/heading";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Separator } from "@/components/ui/separator";
import { Checkbox } from "@/components/ui/checkbox";
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { zodResolver } from "@hookform/resolvers/zod";
import { ColumnDef, createColumnHelper } from "@tanstack/react-table";
import { Edit, MoreHorizontal, Trash } from "lucide-react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { AlertModal } from "@/components/modal/alert-modal";
import { HisMedicineI } from "@/types";
import PageContainer from "@/components/layout/page-container";
// import CustomTable from "@/components/ui/custom-table";
import CustomDndTable from "@/components/ui/custom-dnd-table";
import { useToast } from "@/hooks/use-toast";
import { Plus } from "lucide-react";
import {
  createHisMedicine,
  updateHisMedicine,
  searchHisMedicineList,
  deleteHisMedicine,
} from "@/api";
import { useSearchParams, Link } from "react-router-dom";
import request, { CustomResponse } from "@/api/http_class";

const formSchema = z.object({
  id: z.string().optional(),
  name: z.string().trim().min(3, { message: "中名称至少3个字符" }),
  description: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  chargeCode: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  serial: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  atcCode: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  drugname: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  drugType: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  pinyin: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  py: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  specification: z.string().trim().min(3, { message: "描述信息至少3个字符" }),
  miniUnit: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  packSize: z.number().min(0),
  cadn: z.string().trim().min(3, { message: "描述信息至少3个字符" }).optional(),
  commercialName: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  retailPrice: z.number().min(0),
  mzChargeType: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  zyChargeType: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  manufacture: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  cfdalink: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  deletedFlag: z.number().optional(),
  mzOpenFlag: z.number().optional(),
  showFlag: z.number().optional(),
  startDate: z.string().datetime(),
  endDate: z.string().datetime().optional(), // 结束日期
  monitorClass: z
    .string()
    .trim()
    .min(3, { message: "描述信息至少3个字符" })
    .optional(),
  dutyAmount: z.number(), // 任务量, check:duty_amount>=0
  batch: z.number(), // 批次
});

type FormValuesT = z.infer<typeof formSchema>;

const page: React.FC = () => {
  const [searchParams] = useSearchParams();
  const { toast } = useToast();

  const [title, setTitle] = React.useState<string>("");
  const [description, setDescription] = React.useState<string>("");
  const [isSubmitting, setIsSubmitting] = React.useState<boolean>(false);
  const [isAlertOpen, setIsAlertOpen] = React.useState<boolean>(false);
  const [isDialogOpen, setIsDialogOpen] = React.useState<boolean>(false);
  const [totalCount, setTotalCount] = React.useState<number>(0);
  const [tenantList, setHisMedicineList] = React.useState<HisMedicineI[]>([]);
  const [formData, setFormData] = React.useState<HisMedicineI>();

  const { loading: loadingList, run } = useRequest(
    (paramsString: string) => searchHisMedicineList(paramsString),
    {
      manual: true,
      defaultParams: [location.search.replace(/^\?/, "")],
      onSuccess(resp, params: any) {
        setHisMedicineList(resp.data.data);
        setTotalCount(resp.data.totalCount);
      },
      onError(e: any, params: any) {
        toast({
          variant: "destructive",
          title: "数据获取失败",
          description: "请检查网络或联系系统管理员",
        });
      },
    }
  );

  React.useEffect(() => {
    run(searchParams.toString());
  }, [searchParams]);

  const onUpdateClick = (event: any, data: HisMedicineI) => {
    setTitle("修改信息");
    form.reset(data);
    setIsDialogOpen(true);
    run(searchParams.toString());
  };

  const onDeleteConfirm = (event: any, data: HisMedicineI) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        deleteHisMedicine(data.id).then((res: any) => {
          console.log(data);
          console.log(res);
          toast({
            title: "删除成功",
            description: "",
          });
          run(searchParams.toString());
        });
      }
    } catch (error: any) {
      console.log(error);
      toast({
        title: "删除失败",
        description: "error",
      });
    } finally {
      setIsSubmitting(false);
      setIsAlertOpen(false);
    }
  };

  // 表格中批量导入数量使用
  const handleUploadSubmit = (values: any): Promise<any> => {
    // console.log(values);
    return new Promise((resolve, reject) => {
      if (values.files.length) {
        const formData = new FormData();
        // 将全部数据转换为FormData格式
        values.files.forEach((item: File) => {
          console.log(item);
          formData.append("files", item);
        });
        console.log(formData);
        request({
          url: `/his-medicine/import/image/`,
          method: "POST",
          data: formData,
          headers: { "Content-Type": "multipart/form-data" },
        }).then(
          (res: any) => {
            console.log(res);
            resolve(res);
            toast({
              variant: "success",
              title: "数据导入成功",
              description: "",
            });
          },
          (err: any) => {
            console.log(err);
            reject(err);
            toast({
              variant: "destructive",
              title: "数据导入失败",
              description: "请检查网络或联系系统管理员",
            });
          }
        );
      } else {
        reject("no files");
      }
    });
  };

  const columnHelper = createColumnHelper<HisMedicineI>();

  const columns = [
    columnHelper.display({
      id: "select",
      header: (props) => {
        // console.log(props);
        if (props && props.table) {
          return (
            <Checkbox
              checked={props.table.getIsAllPageRowsSelected()}
              onCheckedChange={(value) =>
                props.table.toggleAllPageRowsSelected(!!value)
              }
              aria-label="Select all"
            />
          );
        } else {
          return <Checkbox aria-label="Select all" />;
        }
      },
      footer: (props) => props.column.id,
      cell: (props) => {
        console.log(props);
        if (props && props.row) {
          return (
            <Checkbox
              checked={props.row.getIsSelected()}
              onCheckedChange={(value) => props.row.toggleSelected(!!value)}
              aria-label="Select row"
            />
          );
        } else {
          return <Checkbox aria-label="Select row" />;
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("id", {
      id: "id",
      header: "ID",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <Link
              to={"/medicine/info/" + row.getValue("id")}
              target="_blank"
              rel="noreferrer"
            >
              {row.getValue("id")}
            </Link>
          );
        }
      },
      enableSorting: false,
      enableHiding: true,
    }),
    columnHelper.accessor("chargeCode", {
      id: "chargeCode",
      header: "HIS代码",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <Link
              to={"/medicine/info/" + row.getValue("id")}
              target="_blank"
              rel="noreferrer"
            >
              {row.getValue("chargeCode")}
            </Link>
          );
        }
      },
      size: 150,
      minSize: 150,
      enableSorting: true,
      enableHiding: false,
      enableGlobalFilter: true,
    }),
    columnHelper.accessor("serial", {
      id: "serial",
      header: "规格代码",
      enableColumnFilter: false,
    }),
    columnHelper.accessor("drugname", {
      id: "drugname",
      header: "药品名称",
      enableSorting: true,
      enableGlobalFilter: true,
      enableHiding: true,
    }),
    columnHelper.accessor("atcCode", {
      id: "atcCode",
      header: "ATC编码",
    }),
    columnHelper.accessor("specification", {
      id: "specification",
      header: "规格",
    }),
    columnHelper.accessor("retailPrice", {
      id: "retailPrice",
      header: "零售价",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <div className="text-right font-medium">
              ￥{(row.getValue("retailPrice") as Number).toFixed(2)}
            </div>
          );
        }
      },
    }),
    columnHelper.display({
      id: "statement",
      header: "说明书",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <a
              href={
                "http://10.2.3.199:9999/zlcx/data_detail.action?webHisId=" +
                row.getValue("chargeCode") +
                (row.getValue("serial") || "01") +
                "&hospitalCode=08110010"
              }
              target="_blank"
              rel="noreferrer"
            >
              说明书
            </a>
          );
        }
      },
      enableResizing: false,
      size: 150,
    }),
    columnHelper.accessor("mzChargeType", {
      id: "mzChargeType",
      header: "门诊费用类别",
      minSize: 120,
    }),
    columnHelper.accessor("mzOpenFlag", {
      id: "mzOpenFlag",
      header: "门诊是否开放",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          if (row.getValue("mzOpenFlag")) {
            return <span>开放</span>;
          } else {
            return <span>未开放</span>;
          }
        }
      },
      minSize: 120,
    }),
    columnHelper.display({
      id: "actions",
      header: "操作",
      cell: (props) => {
        if (props && props.row) {
          const { row } = props;
          return (
            <>
              <AlertModal
                isOpen={isAlertOpen}
                onClose={() => setIsAlertOpen(false)}
                onConfirm={() => onDeleteConfirm(event, row.original)}
                loading={isSubmitting}
              />
              <DropdownMenu modal={false}>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" className="h-8 w-8 p-0">
                    <span className="sr-only">选项</span>
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end">
                  <DropdownMenuLabel></DropdownMenuLabel>
                  <DropdownMenuItem
                    onClick={() => onUpdateClick(event, row.original)}
                  >
                    <Edit className="mr-2 h-4 w-4" /> 更新
                  </DropdownMenuItem>
                  {/* <DropdownMenuItem onClick={() => setIsAlertOpen(true)}>
                  <Trash className="mr-2 h-4 w-4" /> 删除
                </DropdownMenuItem> */}
                </DropdownMenuContent>
              </DropdownMenu>
            </>
          );
        }
      },
    }),
  ];

  // 表单部分
  const form = useForm<FormValuesT>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      id: undefined,
      name: "",
      description: "",
    }, // 初始值不能为undefined，否则不能用form.reset()设置表单值，会报警告：Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
  });

  const onFormSubmit = async (data: FormValuesT) => {
    try {
      setIsSubmitting(true);
      if (data.id) {
        updateHisMedicine(data).then((res) => {
          console.log(res);
          run(searchParams.toString());
        });
      } else {
        createHisMedicine(data).then((res) => {
          console.log(res);
          run(searchParams.toString());
        });
      }
      setIsSubmitting(false);
      setIsDialogOpen(false);
      form.reset();
      toast({
        variant: "success",
        title: "数据提交成功",
        description: "",
        duration: 1600,
      });
    } catch (error: any) {
      toast({
        variant: "destructive",
        title: "数据提交失败",
        description: "请检查网络或联系系统管理员",
      });
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <PageContainer>
      <div className="space-y-4">
        {/* <Breadcrumbs items={breadcrumbItems} /> */}

        <div className="flex items-start justify-between">
          <Heading title={`HIS药品列表`} description="" />

          <Button
            className="p-2 rounded-md hidden"
            onClick={() => {
              form.reset();
              setTitle("创建信息");
              setIsDialogOpen(!isDialogOpen);
            }}
          >
            <Plus className="mr-2 h-4 w-4" />
            创建
          </Button>
        </div>
        <Separator />

        <CustomDndTable
          columns={columns}
          initColumnVisibility={{ select: false, id: false }}
          defaultFilterColumn="drugname"
          data={tenantList}
          loading={loadingList}
          showImportButton={true}
          onSubmitFiles={handleUploadSubmit}
          totalCount={totalCount}
        />

        <Dialog
          open={isDialogOpen}
          onOpenChange={() => setIsDialogOpen(!isDialogOpen)}
        >
          <DialogContent>
            <DialogHeader>
              <DialogTitle></DialogTitle>
              <DialogDescription></DialogDescription>
            </DialogHeader>
            <div className="flex items-center justify-between">
              <Heading title={title} description={description} />
            </div>
            <Separator />
            <Form {...form}>
              <form
                onSubmit={form.handleSubmit(onFormSubmit)}
                className="w-full space-y-8"
              >
                {/* <div className="gap-8 md:grid md:grid-cols-3"> */}
                <div className="flex flex-col gap-4">
                  {formData && formData.id ? (
                    <FormField
                      control={form.control}
                      name="id"
                      render={({ field }) => (
                        <FormItem>
                          <FormLabel>ID</FormLabel>
                          <FormControl>
                            <Input
                              placeholder="id"
                              {...field}
                              disabled={formData && formData.id ? true : false}
                            />
                          </FormControl>
                          <FormMessage />
                        </FormItem>
                      )}
                    />
                  ) : null}
                  <FormField
                    control={form.control}
                    name="drugname"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>药品名称</FormLabel>
                        <FormControl>
                          <Input
                            disabled={isSubmitting}
                            placeholder="HisMedicine name"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                  <FormField
                    control={form.control}
                    name="description"
                    render={({ field }) => (
                      <FormItem>
                        <FormLabel>描述</FormLabel>
                        <FormControl>
                          <Textarea
                            disabled={isSubmitting}
                            placeholder="HisMedicine description"
                            {...field}
                          />
                        </FormControl>
                        <FormMessage />
                      </FormItem>
                    )}
                  />
                </div>
                <Button
                  disabled={isSubmitting}
                  className="ml-auto"
                  variant="ghost"
                  type="submit"
                >
                  提交
                </Button>
              </form>
            </Form>
          </DialogContent>
        </Dialog>
      </div>
    </PageContainer>
  );
};

export default page;
